package com.voxel.sense.infomsg.module.firm.details.chars;

import android.os.Handler;
import android.os.Message;
import android.support.v7.util.DiffUtil;
import android.text.TextUtils;

import com.example.com.common.app.BaseRecyclerPresenter;
import com.example.com.common.factory.data.DataSource;
import com.example.com.common.utils.L;
import com.voxel.sense.infomsg.data.bean.MultiItemBean;
import com.voxel.sense.infomsg.data.bean.RealDataBean;
import com.voxel.sense.infomsg.utils.manager.QueryConfigManager;
import com.voxel.sense.infomsg.widget.SourceCharDiffUtilsCallBack;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Timer;

import cyy.example.com.facotry.constants.Constants;
import cyy.example.com.facotry.model.api.BaseEntity;
import cyy.example.com.facotry.model.api.response.RealDataEntity;
import cyy.example.com.facotry.net.RequestIdFactory;
import cyy.example.com.facotry.net.helper.FirmNetHelper;
import cyy.example.com.facotry.share.SPEngine;


/**
 * Created by ChenYiYao on 2018/2/27.
 */

public class SourceCharDataPresenter extends BaseRecyclerPresenter<SourceCharDataContract.View>
        implements SourceCharDataContract.Presenter, DataSource.Callback<BaseEntity<List<RealDataEntity>>> {
    public final static long SLEEP_TIME = 1000 * 5; //轮询刷新时间
    private Timer mTimer;
    private Handler mHandler;
    private List<MultiItemBean> mList;
    final private static int DATA_REFRESH = 200;
    final private static int NOT_DATA = 400;

    public SourceCharDataPresenter(SourceCharDataContract.View view) {
        super(view);
    }

    @Override
    public void start() {
        super.start();
        mHandler = new Handler(new Handler.Callback() {
            @Override
            public boolean handleMessage(Message msg) {
                if (msg.what == DATA_REFRESH) {
                    DiffUtil.DiffResult diffResult = DiffUtil.calculateDiff((DiffUtil.Callback) msg.obj);
                    DiffRefreshData(diffResult, mList);
                } else if (msg.what == NOT_DATA) {
                    mTimer.cancel();
                    mView.onAdapterDataChanged();
                }
                return false;
            }
        });
        mList = new ArrayList();
    }

    @Override
    public void destroy() {
        super.destroy();
        if (mTimer != null) {
            mTimer.cancel();
            mTimer = null;
        }
    }

    @Override
    public void pollingData(final String sitecode) {
        if (mTimer == null) {
            mTimer = new Timer();
        } else {
            mTimer.cancel();
        }
        //获取从服务器拿去回来的刷新时间
        long realDataRefreshTime = SPEngine.getSPEngine().getRealDataRefreshTime();
        if (realDataRefreshTime == 0) {
            //还没有从网络拿到时间，则去网络加载
            QueryConfigManager.getInstance().getAppConfig(true);
        }
        mView.onLoading();
        FirmNetHelper.getFirmRealData(sitecode, "",SourceCharDataPresenter.this);


//        设置定时器，不断的刷新数据
//        mTimer.schedule(new TimerTask() {
//            @Override
//            public void run() {
//                L.d("网络加载实时的数据");
//                //判断是否有网络
//                if (companyName != null && NetworkUtils.isConnected()) {
//                    FirmNetHelper.getFirmRealData(companyName, SourceCharDataPresenter.this);
//                } else {
//                    //需要在主线程操作ui
//                    mHandler.post(new Runnable() {
//                        @Override
//                        public void run() {
//                            mView.onAdapterDataChanged();
//                        }
//                    });
//
//                }
//            }
//        }, 0, realDataRefreshTime != 0 ? realDataRefreshTime : SLEEP_TIME);
    }

    @Override
    public void onDataLoaded(final BaseEntity<List<RealDataEntity>> data, int reqId) {
        if (mView == null)
            return;

        if (reqId == RequestIdFactory.GET_FIRM_REAL_DATA) {
            if (data.isSuccess() && data.getData() != null && data.getData().size() > 0) {
//                每个元素最新的数据
                new Thread(new Runnable() {
                    @Override
                    public void run() {
//                    分别构造超标数据，表格数据，图标数据类型的数据
                        mList.clear();
                        List items = mView.getRecyclerViewAdapter().getItems();
                        List<RealDataEntity> entities = data.getData();
                        List<MultiItemBean> realCharData = createRealCharData(entities);
                        mList.addAll(realCharData);
                        Message message = mHandler.obtainMessage();
                        if (mList.size() > 0) {
                            L.d("-----------------mList.size()：" + mList.size());
                            DiffUtil.Callback callback = new SourceCharDiffUtilsCallBack(items, mList);
                            message.obj = callback;
                            message.what = DATA_REFRESH;
                        } else {
                            message.what = NOT_DATA;
                            //没有数据，结束刷新
                        }
                        message.sendToTarget();
                    }
                }).start();
            } else {
                mTimer.cancel();
                mView.onAdapterDataChanged();
            }
        }
    }

    @Override
    public void onDataNotAvailable(String strRes, int reqId) {
        if (mView == null)
            return;
        mView.showEmptyView(strRes, true);
    }

    /**
     * 构造图表实时数据实体
     */
    private List<MultiItemBean> createRealCharData(List<RealDataEntity> datas) {

        //列表的数据集
        List<MultiItemBean> list = new ArrayList();

        RealDataEntity data = datas.get(0);
        if (datas != null) {
            //组装数据
            Map<String, String> analysisVo = data.getAnalysisVo();
            Map<String, String> paramNameMap = data.getParamNameMap();
            Map<String, String> paramUnitMap = data.getParamUnitMap();

            if ((analysisVo != null && analysisVo.size() > 0)
                    && paramNameMap != null && paramNameMap.size() > 0
                    && paramUnitMap != null && paramUnitMap.size() > 0) {
                //柱状图的数据集
                List<RealDataBean> charList = new ArrayList();

                Set<String> keys = analysisVo.keySet();
                for (String key : keys) {
                    //在元素数值中的集合中，在第一个字符中有个p，这里去除
                    String subKey = key.substring(1);
                    String name = paramNameMap.get(subKey);
                    if (TextUtils.isEmpty(name) || "id".equals(key)) {
                        continue;//跳过可以为id和没有元素名称的项
                    }
                    String unit = paramUnitMap.get(subKey);
                    String value = analysisVo.get(key);
                    RealDataBean realDataBean = new RealDataBean(unit, name, 0, value, "");
                    MultiItemBean itemBean = new MultiItemBean(realDataBean, Constants.NORMAL_TYPE);
                    list.add(itemBean);
                    charList.add(realDataBean);
                }
                if (charList.size() > 0) {
                    MultiItemBean itemBean = new MultiItemBean(charList, Constants.REAL_TABLE_CHAR_TYPE);
                    list.add(itemBean);
                }

            }
        }
        return list;
    }

}
